package org.example.test;

/**
 * org.example.test
 *
 * @author 莫磊
 * @description
 * @date 2025/7/25
 */
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.time.Duration;
import java.time.Instant;
import org.apache.hc.core5.util.Timeout;

public class SpeedTester {

	private static final String TEST_URL = "https://example.com";

	public static int testProxySpeed(String host, int port) {
		// ✅ 使用 HttpHost 设置代理
		HttpHost proxyHost = new HttpHost(host, port);

		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(Timeout.ofSeconds(5))
				.setResponseTimeout(Timeout.ofSeconds(10))
				.build();

		try (CloseableHttpClient httpClient = HttpClients.custom()
				.setProxy(proxyHost)  // ✅ 正确使用 HttpHost
				.setDefaultRequestConfig(requestConfig)
				.build()) {

			HttpUriRequest request = new HttpGet(TEST_URL);
			Instant start = Instant.now();
			ClassicHttpResponse response = httpClient.executeOpen(null, request, null);
			httpClient.execute(request, resp -> {
				EntityUtils.consume(resp.getEntity());
				return null;
			});
			Instant end = Instant.now();

			return (int) Duration.between(start, end).toMillis();
		} catch (Exception e) {
			System.err.println("Error testing " + host + ":" + port + ": " + e.getMessage());
			return -1;
		}
	}
}